<template>
  <div class="assign-role">
    <div class="my-tree">
      <el-tree
        ref="treeRef"
        :data="list"
        :props="defaultProps"
        show-checkbox
        check-strictly
        node-key="id"
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
      />
    </div>
    <div class="role-btn">
      <el-button type="primary" @click="onSubmit">确认</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getAllPremissionRequest } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { assignPermissionRequest, getRoleDetailByIdRequest } from '@/api/setting'

export default {
  name: 'AssignPermission',
  props: {
    roleDialogVisble: {
      type: Boolean,
      default: false
    },
    currentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getPermission()
    this.getRoleDetailById(this.currentId)
  },
  methods: {
    onSubmit() {
      this.assignPermission()
      this.$emit('close')
    },
    cancel() {
      this.$emit('close')
    },
    async getPermission() {
      try {
        const res = await getAllPremissionRequest()
        if (res.success) {
          console.log('服务器的返回：', res.data)
          this.list = tranListToTreeData(res.data, '0')
          console.log('转换为树形结构之后的数据：', this.list)
        } else {
          this.$message.error('获取权限接口失败')
        }
      } catch (err) {
        console.log('getPermissionRequest: ', err)
      }
    },
    handleNodeClick(data) {
      console.log(data)
    },
    handleCheckChange() {
    //   console.log(this.$refs.treeRef.getCheckedKeys())
    },
    // 分配权限的异步请求
    async assignPermission() {
      try {
        const res = await assignPermissionRequest({
          id: this.currentId,
          permIds: this.$refs.treeRef.getCheckedKeys()
        })
        if (res.success) {
          console.log('assignPermissionRequest: ', res)
        } else {
          this.$message('分配权限失败')
        }
      } catch (err) {
        console.log('assignPermissionRequest: ', err)
      }
    },
    // 根据id数据回显的异步请求
    async getRoleDetailById(id) {
      try {
        const res = await getRoleDetailByIdRequest(id)
        if (res.success) {
          this.$refs.treeRef.setCheckedKeys(res.data?.permIds || [])
          console.log('getRoleDetailByIdRequest: ', res)
        } else {
          this.$message('当前用户的详情接口失败')
        }
      } catch (err) {
        console.log('getRoleDetailByIdRequest: ', err)
      }
    }
  }
}
</script>
